import { defineStore } from 'pinia'
import { reactive, ref, toRefs } from 'vue'
import { getCurrentUserApi } from '@/api/user.js'

const useUserStore = defineStore(
  'user',
  () => {
    const state = reactive({
      userInfo: {},
      token: '',
      timer:null
    })

    const getUserInfo = () => {
      return new Promise((resolve, reject) => {
        getCurrentUserApi()
          .then(async (res) => {
            if (res) {
              state.userInfo = res.user
              if(!state.timer){
                console.log('开启计时器')
                state.timer = setInterval(()=>{
                  getUserInfo()
                },1000*60*20)
              }
              resolve(res)
            } else {
              reject(res)
            }
          })
          .catch((e) => {
            reject(e)
          })
      })
    }


    return {
      getUserInfo,
      ...toRefs(state)
    }
  },
  {
    persist: {
      storage: sessionStorage,
      paths: ['token', 'userInfo']
    }
  }
)

export default useUserStore
